<template>
    <el-card class="box-card main-card">
        <div slot="header" class="clearfix">
            <span>{{title}}</span>
            <el-button style="float: right;" size="small" @click="$emit('cancel')">返回</el-button>
        </div>
        <div>
            <el-form :model="form" ref="form" :rules="rules" label-width="80px">
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="登录名" prop="username" >
                            <el-input v-model="form.username" placeholder="请输入登录名" style="width: 80%"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="密码" prop="password" v-if="form.id == null">
                            <el-input v-model="form.password" type="password" placeholder="请输入登录密码" style="width: 80%"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="性别" prop="sex" >
                            <el-select v-model="form.sex" placeholder="请选择性别" style="width: 80%">
                                <el-option :value="0" label="男"/>
                                <el-option :value="1" label="女"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="昵称" prop="nickName" >
                            <el-input v-model="form.nickName" style="width: 80%"/>
                        </el-form-item>
                    </el-col>
                </el-row>
        
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="电话号码" prop="phoneNumber" >
                            <el-input v-model="form.phoneNumber" style="width: 80%" placeholder="请输入电话号码"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="电子邮箱" prop="email" >
                            <el-input v-model="form.email" style="width: 80%" placeholder="请输入电子邮箱"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="居住地址" prop="address" >
                            <el-input
                                type="textarea"
                                autosize
                                placeholder="请输入居住住址"
                                v-model="form.address"
                                style="width: 80%"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="用户角色" prop="roles"  >
                            <el-select v-model="roles"  placeholder="请选择角色信息" style="width: 80%" multiple>
                                <el-option v-for="(role,index) in roleList" :key="index" :label="role.label" :value="role.id"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="11">
                        <el-form-item label="是否启用" prop="status" >
                            <el-radio-group v-model="form.status">
                                <el-radio :label="true" >是</el-radio>
                                <el-radio :label="false" >否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <!--
                            action: 用户上传地址
                            show-file-list: 是否展示列表
                        -->
                        <el-form-item label="用户头像" prop="avatar" >
                            <el-upload
                                class="avatar-uploader"
                                :action="action"
                                :headers="headers"
                                :show-file-list="false"
                                :on-success="handleSuccess"
                                :before-upload="beforeUpload">
                                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="$emit('cancel')">取 消</el-button>
                <el-button type="primary" @click="clickOk">确 定</el-button>
            </div>
        </div>

    </el-card>
</template>

<script>
export default {
    data(){
        return {
            fileList: [{
                name: 'food.jpeg', 
                url: ''
            }],
            imageUrl: null,
            rules:{
                username:[
                    { required: true, message: '请输入登录名', trigger: 'blur' },
                    {min:2 , max: 50, message: "登录名的长度为2~50",trigger: 'blur'}
                ],
                password:[
                    { required: true, message: '请输入登录密码', trigger: 'blur' },
                    {min:6 , max: 32, message: "用户标签值的长度为6~32",trigger: 'blur'}
                ],
                sex:[
                    { required: true, message: '请选择性别', trigger: 'blur' },
                ],
                phoneNumber:[
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    { message: "手机号码输入不正确",pattren: /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/ }
                ],
                avatar:[
                    {
                        required: true,
                        validator:(rule,value,callback)=>{
                            if (this.form.avatar === null || this.form.avatar === '' || this.form.avatar === undefined){
                                callback(new Error('请上传用户头像'))
                            }else {
                                callback();
                            }
                        },
                        trigger: 'blur'
                        
                    }
                ]
            },
            action:'/tool/upload',
            headers:{
                Authorization: sessionStorage.getItem("token")
            },
            roleList:{},
            roles:[]
        }
    },
    created(){
        this.findAllRoles();
    },
    methods:{
        findAllRoles(){
            this.$ajax.get("/role/findAllRoles").then(res =>{
                this.roleList = res.data.data;
                console.log("可供选择的角色信息",this.roleList);
            });
        },
        
        /*性别格式化*/
        formatSex(row){
            if (row.sex === 0){
                return "男"
            }else if (row.sex === 1){
                return "女"
            }else{
                return "未知"
            }
        },
    
        clickCancel(){
        },
        /**
         * 头像上传成功
         * res:返回的参数
         * file:上传的文件信息
         * **/
        handleSuccess(res,file){
            this.imageUrl = this.$qiniu + res.data;
            this.form.avatar = this.imageUrl;
            console.log(res);
            console.log(this.imageUrl);
            
        },
        /**
         *头像上传之前
         * 可以判断文件格式，文件大小
         * **/
        beforeUpload(file){
            let index = file.name.lastIndexOf('.');
            let suffix = file.name.substring(index +1);
         //   if (suffix !== 'jpg' && suffix !== 'png' && suffix !== 'jpeg' ){
          //      this.$message.warning("请上传jpg、png、jpeg类型的图片")
          //      return false;
         //   }
            //判断文件大小，不能超过10M
            if (file.size > 10*1024*1024){
                this.$message.warning("文件大小不能超过10M")
                return false;
            }
            
        },
        /**
         * 点击ok
         */
        clickOk(){
            //进行表单校验
            this.imageUrl = null;
            this.$refs.form.validate((valid) =>{
                //校验不通过
                if(!valid) return this.$message.error('表单校验不通过，请检查后提交！');
                    let arr = [];
                    this.roles.forEach(item =>{
                        arr.push({id : item});
                    })
                    this.form.roles = arr;
                //校验通过 判断是否是新增
                if(this.form.id === undefined || this.form.id ===null){
                    console.log("用户信息为",this.form);
                    this.$ajax.post("/user/insert",this.form).then((res)=>{
                        this.$message.success(res.data.message)
                        return this.$emit('cancel');
                    })
                }else {
                    this.$ajax.put('/user/update',this.form).then((res)=>{
                        this.$message.success(res.data.message)
                        return this.$emit('cancel');
                    })
                }
            })
        },
        
    },
    props:['title','form']
    ,
    watch:{
        'title':{
            handler(val,old){
                
                console.log(val,old);
            }
        },
        'form':{
            handler(val,old){
                this.roles = [];
                this.imageUrl = val.avatar;
               if (val.roles && val.roles.length>0){
                   val.roles.forEach(item=>{
                       this.roles.push(item.id);
                   })
               }
               
            }
        },
    },
    
};
</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 130px;
    height: 130px;
    line-height: 130px;
    text-align: center;
}
.avatar {
    width: 130px;
    height: 130px;
    display: block;
}
.clearfix{
    text-align: left;
}
</style>